package com.hengmei.smallscreen.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hengmei.smallscreen.widget.ClickAction
import com.hjq.language.MultiLanguages
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext


abstract class BaseActivity<VB : ViewBinding>(private val inflate: (LayoutInflater) -> VB) : AppCompatActivity() ,
  ClickAction, CoroutineScope {

  lateinit var binding: VB
  lateinit var me: Context


  lateinit var job: Job

  override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

  override fun onCreate(savedInstanceState: Bundle?) {
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去除标题
    super.onCreate(savedInstanceState)
    me = this
    binding = inflate(layoutInflater)
    setContentView(binding.root)

    // 隐藏状态栏
    val intent = Intent("hide.systemui")
    sendBroadcast(intent)

    ImmersionBar.with(this) .fullScreen(true) .hideBar(BarHide.FLAG_HIDE_BAR) .init()

    job = Job()
    initView()

    initViewEvents()
  }
  abstract fun initView()

  abstract fun initViewEvents()

  //更好用的跳转方式
  open fun jump(cls: Class<*>?): Boolean {
    try {
      startActivity(Intent(me, cls))
    } catch (e: Exception) {
      e.printStackTrace()
      return false
    }
    return true
  }
  override fun attachBaseContext(newBase: Context?) {
    // 绑定语种
    super.attachBaseContext(MultiLanguages.attach(newBase))
  }
  /**
   * 初始化软键盘
   */
  protected open fun initSoftKeyboard() {
    // 点击外部隐藏软键盘，提升用户体验
    getContentView()?.setOnClickListener { hindSoftKeyboard() }
  }
  open fun getContentView(): ViewGroup? {
    return findViewById(Window.ID_ANDROID_CONTENT)
  }

  /**
   * 隐藏软键盘
   */
  private fun hindSoftKeyboard() {
    // 隐藏软键盘，避免软键盘引发的内存泄露
    val view = currentFocus
    if (view != null) {
      val manager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
      if (manager.isActive(view)) {
        manager.hideSoftInputFromWindow(
          view.windowToken,
          InputMethodManager.HIDE_NOT_ALWAYS
        )
      }
    }
  }
  /*
    *  界面结束 关掉协程
    * */
  override fun onDestroy() {
    super.onDestroy()
    // 关闭页面后，结束所有协程任务
    job.cancel()
  }
}